﻿using System;
using System.Collections.Generic;
using System.IO;

namespace PhotoManager
{
    /// <summary>
    /// Maintains a collection of photo items.
    /// </summary>
    public class PhotoCollection : IDisposable
    {
        private readonly Dictionary<string, PhotoItem> m_photos =
            new Dictionary<string, PhotoItem>(); // LCase(FileName) => PhotoItem

        private readonly PhotoInfoCache m_cache;

        public PhotoCollection(string cacheFileName)
        {
            if (cacheFileName == null)
                throw new ArgumentNullException("cacheFileName");

            m_cache = new PhotoInfoCache(cacheFileName);
        }

        public PhotoItem Add(FileInfo fileInfo)
        {
            if (fileInfo == null)
                throw new ArgumentNullException("file");

            PhotoInfo photoInfo = m_cache.FindPhotoInfo(fileInfo);
            if (photoInfo == null)
            {
                photoInfo = new PhotoInfo(fileInfo.FullName);
                m_cache.AddPhotoInfo(fileInfo, photoInfo);
            }

            PhotoItem item = new PhotoItem(fileInfo, photoInfo);
            m_photos[item.FileInfo.FullName.ToLowerInvariant()] = item;
            return item;
        }

        public IEnumerable<PhotoItem> Items
        {
            get { return m_photos.Values; }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected void Dispose(bool disposing)
        {
            if (disposing)
                m_cache.Dispose();
        }
    }
}
